package com.nexus.plugin.amqp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexus.core.properties.ExternalPropertySourceFactory;
import com.nexus.plugin.amqp.handle.EnhancedConfirmCallback;
import com.nexus.plugin.amqp.handle.EnhancedReturnsCallback;
import com.nexus.plugin.amqp.template.NexusRabbitTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Amqp配置
 *
 * @Date 2025/9/23 12:30
 * @Author luzhengning
 **/
@Configuration
@org.springframework.context.annotation.PropertySource(
        name = "amqp.properties",
        value = "classpath*:amqp-pro.properties", encoding = "UTF8",
        factory = ExternalPropertySourceFactory.class,
        ignoreResourceNotFound = true
)
@Slf4j
public class NexusPluginAmqpConfig {

    /**
     * 增强的RabbitTemplate
     *
     * @Date 2025/9/26 17:10
     * @Author luzhengning
     **/
    @Bean
    public NexusRabbitTemplate nexusRabbitTemplate(ConnectionFactory connectionFactory,
                                                   MessageConverter messageConverter) {
        NexusRabbitTemplate rabbitTemplate = new NexusRabbitTemplate(connectionFactory);
        //JSON序列化
        rabbitTemplate.setMessageConverter(messageConverter);
        //确保消息无法路由时能触发返回回调
        rabbitTemplate.setMandatory(true);
        //消息确认回调
        rabbitTemplate.setConfirmCallback(new EnhancedConfirmCallback());
        rabbitTemplate.setReturnsCallback(new EnhancedReturnsCallback());

        log.info("增强RabbitTemplate配置完成");
        return rabbitTemplate;
    }

    /**
     * 配置JSON消息转换器
     *
     * @Date 2025/9/24 03:09
     * @Author luzhengning
     **/
    @Bean
    @ConditionalOnMissingBean
    public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
